import {
  CELL
} from "./cell.js"
import Fleld from "./field.js"
import {initLoad} from './img.js'

// konva 配置
const configKonva = {
  width: 250,
  height: 300
}
// 背景配置
const bgRect = {
  x: 0,
  y: 0,
  width: configKonva.width,
  height: configKonva.height,
  fill: '#848484',
}


// 游戏配置
export const Level = {
  low: {
    row: 9,
    col: 9,
    mines: 10
  },
  middle: {
    row: 16,
    col: 16,
    mines: 40
  },
  hard: {
    row: 30,
    col: 16,
    mines: 99
  },
  fullScreen: null
}

export class Game {
  // 初始化
  constructor() {
    // 场景参数
    this.configKonva = configKonva
    this.bgRect = bgRect

    // 游戏参数
    this.level = null
    this.time = 0
    this.t = null // 计时器
    this.flags = 0 // flags剩余数量
    this.status = 0 // 游戏状态 -1未开始 0进行中 1通关 2失败
    this.cloaks = 0 // 未开的格子

    // 游戏实例对象
    this.Vue = null
    this.field = new Fleld(this)

    initLoad()
  }

  // 设置vue实例
  setVue(vue) {
    this.Vue = vue
  }
  // 满屏参数
  fullScreen() {
    let level = {
      row: Math.trunc((document.documentElement.clientWidth - 20) / (CELL.width + CELL.margin)),
      col: Math.trunc((document.documentElement.clientHeight - 120) / (CELL.height + CELL.margin)),
      mines: 0
    }
    level.mines = Math.trunc(level.row * level.col * 0.18)
    return level
  }
  // 设置难度
  setLevel(level) {
    this.level = level
    if (!this.level) this.level = this.fullScreen()
    this.flags = this.level.mines
    this.configKonva.width = this.level.row * (CELL.width + CELL.margin) + 4 // 2 边距
    this.bgRect.width = this.level.row * (CELL.width + CELL.margin)
    this.bgRect.height = this.configKonva.height = this.level.col * (CELL.width + CELL.margin)

    this.start()
  }
  // 开启计时器
  startTime() {
    this.t = setInterval(() => {
      this.time++
    }, 1000);
  }
  // 游戏开始
  start() {
    this.status = -1 // 准备开始阶段
    this.reset()
    this.field.createField()
    this.field.createMines()
    this.field.createNumber()
    setTimeout(() => {
      this.field.initOpen()
    }, 100);
    this.Vue.reset()
  }
  // 游戏重置
  reset() {
    clearInterval(this.t)
    this.flags = this.level.mines
    this.cloaks = this.level.row * this.level.col
    this.time = 0
    this.field.reset()
  }
  // 游戏结束1 踩雷
  gameover() {
    clearInterval(this.t)
    this.status = 2
    this.field.showMines()
  }
  // 游戏结束2 通关
  gamepass() {
    clearInterval(this.t)
    this.status = 1
  }
}
